package com.example.sport.controller;

import com.alibaba.fastjson.JSON;
import com.example.sport.pojo.QueryInfo;
import com.example.sport.pojo.User;
import com.example.sport.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class UserController {

    @Autowired
    UserService userService;

    /**
     * 模糊查询用户并分页显示
     *
     * @param queryInfo 包含了用户名，当前页，每页显示最大数量
     * @return res集合的json字符串，里面有模糊查询出的用户个数，和用户所有信息
     */
    @RequestMapping("/allUser")
    public String getUser(QueryInfo queryInfo) {
        queryInfo.setQuery("%" + queryInfo.getQuery() + "%");
        Map<String, Object> res = userService.getUserList(queryInfo);

        //SpringBoot的RestController可以将返回的都自动转成json字符串，所以这里其实可以不用转化，直接返回res
        return JSON.toJSONString(res);
    }

    @RequestMapping("/userState")
    public String updateState(@RequestParam("id") Integer id,
                              @RequestParam("state") Boolean state) {
        int res = userService.updateState(id, state);
        return res > 0 ? "success" : "error";
    }

    @RequestMapping("/addUser")
    public String addUser(@RequestBody User user) {
        user.setRole("普通用户");
        user.setState(false);
        int res = userService.addUser(user);
        return res > 0 ? "success" : "error";
    }

    @RequestMapping("/deleteUser")
    public String deleteUser(@RequestParam("id") Integer id){
        int res=userService.deleteUser(id);
        return res > 0 ? "success" : "error";
    }

    @RequestMapping("/getUpdate")
    public String getUpdateUser(@RequestParam("id")Integer id){
        User user=userService.getUserById(id);
        return JSON.toJSONString(user);
    }

    @RequestMapping("/editUser")
    public String updateUser(@RequestBody User user){
        int res=userService.updateUser(user);
        return res > 0 ? "success" : "error";
    }
}